import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Permission, PermissionGroup } from '../../entities/permission.entity';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    private permissionRepository: Repository<Permission>,
  ) {}

  async createPermission(
    name: string,
    code: string,
    group: PermissionGroup,
    description?: string,
  ) {
    const existingPermission = await this.permissionRepository.findOne({
      where: [{ name }, { code }],
    });

    if (existingPermission) {
      throw new BadRequestException('权限名称或代码已存在');
    }

    const permission = this.permissionRepository.create({
      name,
      code,
      group,
      description,
    });

    return this.permissionRepository.save(permission);
  }

  async updatePermission(
    id: string,
    name?: string,
    code?: string,
    group?: PermissionGroup,
    description?: string,
  ) {
    const permission = await this.permissionRepository.findOne({
      where: { id },
    });

    if (!permission) {
      throw new NotFoundException('权限不存在');
    }

    if (name && name !== permission.name) {
      const existingPermission = await this.permissionRepository.findOne({
        where: { name },
      });
      if (existingPermission) {
        throw new BadRequestException('权限名称已存在');
      }
      permission.name = name;
    }

    if (code && code !== permission.code) {
      const existingPermission = await this.permissionRepository.findOne({
        where: { code },
      });
      if (existingPermission) {
        throw new BadRequestException('权限代码已存在');
      }
      permission.code = code;
    }

    if (group) {
      permission.group = group;
    }

    if (description !== undefined) {
      permission.description = description;
    }

    return this.permissionRepository.save(permission);
  }

  async deletePermission(id: string) {
    const permission = await this.permissionRepository.findOne({
      where: { id },
      relations: ['roles'],
    });

    if (!permission) {
      throw new NotFoundException('权限不存在');
    }

    if (permission.roles?.length > 0) {
      throw new BadRequestException('该权限已被角色使用，无法删除');
    }

    await this.permissionRepository.remove(permission);
    return { message: '权限删除成功' };
  }

  async getPermissions() {
    return this.permissionRepository.find({
      order: {
        group: 'ASC',
        createdAt: 'DESC',
      },
    });
  }

  async getPermissionsByGroup(group: PermissionGroup) {
    return this.permissionRepository.find({
      where: { group },
      order: { createdAt: 'DESC' },
    });
  }

  async getPermissionById(id: string) {
    const permission = await this.permissionRepository.findOne({
      where: { id },
      relations: ['roles'],
    });

    if (!permission) {
      throw new NotFoundException('权限不存在');
    }

    return permission;
  }
} 